package android.serialport;

import android.content.Context;
import android.widget.Toast;

import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class SerialPort {
    private static final String TAG = "SerialPort";
    private String error;
    private boolean flag = false;
    private FileDescriptor mFd;
    private FileInputStream mFileInputStream;
    private FileOutputStream mFileOutputStream;

    static {
        System.loadLibrary("serial_port");
    }

    public SerialPort(File paramFile, int paramInt1, int paramInt2, Context paramContext)
            throws SecurityException, IOException {
        if ((!paramFile.canRead()) || (!paramFile.canWrite())) ;
        try {
            Process localProcess = Runtime.getRuntime().exec("/system/xbin/su");
            StringBuilder localStringBuilder = new StringBuilder();
            localStringBuilder.append("chmod 777 ");
            localStringBuilder.append(paramFile.getAbsolutePath());
            localStringBuilder.append("\nexit\n");
            String str = localStringBuilder.toString();
            localProcess.getOutputStream().write(str.getBytes());
            if ((localProcess.waitFor() == 0) && (paramFile.canRead())) {
                boolean bool = paramFile.canWrite();
                if (bool) {
                    this.mFd = open(paramFile.getAbsolutePath(), paramInt1, paramInt2);
                    FileDescriptor localFileDescriptor = this.mFd;
                    if (localFileDescriptor == null) {
                        this.error = "串口连接失败，系统将不能正常工作，请咨询技术人员!";
                        return;
                    }
                    this.mFileInputStream = new FileInputStream(localFileDescriptor);
                    this.mFileOutputStream = new FileOutputStream(this.mFd);
                    this.flag = true;
                    return;
                }
            }
            this.error = "获取串口权限失败，系统将不能正常工作，请咨询技术人员！";
            return;
        } catch (Exception localException) {
            localException.printStackTrace();
            this.error = "获取串口权限失败，系统将不能正常工作，请咨询技术人员！";
            Toast.makeText(paramContext,localException.getMessage(),Toast.LENGTH_LONG).show();
        }
    }

    private static native FileDescriptor open(String paramString, int paramInt1, int paramInt2);

    public native void close();

    public String getError() {
        return this.error;
    }

    public boolean getFlag() {
        return this.flag;
    }

    public InputStream getInputStream() {
        return this.mFileInputStream;
    }

    public OutputStream getOutputStream() {
        return this.mFileOutputStream;
    }
}